﻿using System;
using System.Collections.Generic;
using System.Text;
using Decal.Adapter;
using Decal.Interop.Core;
using Decal.Adapter.Wrappers;
using System.Text.RegularExpressions;
using System.Linq;

namespace FellowShipHelper
{
    class FellowShipChatManager : IDisposable
    {
        public FellowShipChatManager()
        {
            try
            {
                CoreManager.Current.ChatBoxMessage += new EventHandler<ChatTextInterceptEventArgs>(Current_ChatBoxMessage);

            }
            catch (Exception e)
            {
                Util.LogError(e);
                Util.WriteToChat(e.Message, eChatColors.Red);
            }
        }
        /// <summary>
        /// Used to dispose of this object
        /// </summary>
        public void Dispose()
        {
            try
            {
                // Remove everything we create in this class
                CoreManager.Current.ChatBoxMessage -= new EventHandler<ChatTextInterceptEventArgs>(Current_ChatBoxMessage);
                GC.SuppressFinalize(this);
            }
            catch (Exception e)
            {
                Util.LogError(e);
                Util.WriteToChat(e.Message, eChatColors.Red);
            }
        }
        void Current_ChatBoxMessage(object sender, ChatTextInterceptEventArgs e)
        {
            /*
             * The plugin actually sees the messages before the game
             * displays them in chat, just slightly before. 
             */
            // If nothing is going on, dont worry about it
            if (e.Eat || e.Text == string.Empty) 
                return;
            // We just want Fellowship Messages here
            if (e.Text.StartsWith("[Fellowship]"))
            {
                // We need to parse commands here, and respond to them if they are in our command list.
                // We are a fellowship message
                // get the name of the person who sent this cmd
                string name = Util.GetSourceOfChat(e.Text);
                int player = e.Target;

                if (e.Text.Contains("!comps"))
                {
                    RespondToCommand(name, player, "comps");
                }
            }
        }
        /// <summary>
        /// A command we recieve in fellowship chat
        /// </summary>
        /// <param name="command">the command to check for</param>
        public void RespondToCommand(string sender, int playerId, string command)
        {
            switch (command)
            {
                case "comps":
                    {
                        string reply = string.Empty;
                        int all = 0;
                        reply = "My Main pack has " + Util.GetFreePackSlots(CoreManager.Current.CharacterFilter.Id, out all) + " free slots, I am " +
                            CoreManager.Current.CharacterFilter.Burden + "% burdened. Components i am tracking are ";
                        // What check boxes do we have selected to report on ?
                        if (PluginCore.ManaScarabsCheckBox)
                        {
                            // We want to report our mana scarabs
                            reply += Util.GetItemTotal("Mana Scarab")+" Mana Scarabs ";
                        }

                        if (PluginCore.DarkScarabsCheckBox)
                        {
                            // We want to report our Dark scarabs
                            reply += Util.GetItemTotal("Dark Scarab") + " Dark Scarabs ";
                        }

                        if (PluginCore.DiamondScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Diamond Scarab") + " Diamond Scarabs ";
                        }

                        if (PluginCore.PlatinumScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Platinum Scarab") + " Platinum Scarabs ";
                        }

                        if (PluginCore.PyrealScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Pyreal Scarab") + " Pyreal Scarabs ";
                        }

                        if (PluginCore.GoldScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Gold Scarab") + " Gold Scarabs ";
                        }

                        if (PluginCore.SilverScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Silver Scarab") + " Silver Scarabs ";
                        }

                        if (PluginCore.CopperScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Copper Scarab") + " Copper Scarabs ";
                        }

                        if (PluginCore.IronScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Iron Scarab") + " Iron Scarabs ";
                        }

                        if (PluginCore.LeadScarabsCheckBox)
                        {
                            // We want to report our platinum scarabs
                            reply += Util.GetItemTotal("Lead Scarab") + " Lead Scarabs ";
                        }
                        if (PluginCore.TapersCheckBox)
                        {
                            // We want to report our mana scarabs
                            reply += Util.GetItemTotal("Prismatic Taper") + " Prismatic Tapers ";
                        }
                        ReportToFellowShip(reply);
                    }
                    break;
                default:
                    break;
            }
        }
        public void ReportToFellowShip(string toReport)
        {
            // TODO: Check the length of this string, we have a limit per line
            // 220 chars per line
            if (toReport == string.Empty) { return; }
            // report it
            if (toReport.Length < 220)
            {
                // Just report it
                CoreManager.Current.Actions.InvokeChatParser("/f " + toReport + " -f-");
            }
            else
            {
                // Longer than 220, we need to break it down
                string[] message = SplitIntoChunks(toReport, 220, false);
                foreach (string s in message)
                {
                    CoreManager.Current.Actions.InvokeChatParser("/f " + s + " -f-");
                }
            }
        }
        private static string[] SplitIntoChunks(string text, int chunkSize, bool truncateRemaining)
        {
            string chunk = chunkSize.ToString();
            string pattern = truncateRemaining ? ".{" + chunk + "}" : ".{1," + chunk + "}";

            string[] chunks = null;
            if (chunkSize > 0 && !String.IsNullOrEmpty(text))
                chunks = (from Match m in Regex.Matches(text, pattern) select m.Value).ToArray();

            return chunks;
        }     
    }
}
